<template>


  <div>

    <el-row :gutter="20">

      <!--部门树-->
      <el-col :span="8">
        <el-card style="">

          <el-row :gutter="20">
            <el-col :span="12" >
              <el-input
                placeholder="输入关键字进行过滤"
                size="mini"
                v-model="filterText">
              </el-input>
            </el-col>

            <el-col :span="12" style="line-height: 30px;">
              <span>
              包含全部下级用户 <el-checkbox v-model="checkedAllSub"/>
              </span>
            </el-col>
          </el-row>


            <br/>
            <br/>

            <!-- 节点树-->
            <!--
              indent 是防止树之间的间隔太大，这里要加样式才需要这个
              accordion 同一个节点，一次只能打开一个，防止树太大
            -->
            <el-tree
              class="tree-line" :indent='0'
              :data="tree.dataTree"
              default-expand-all
              node-key="id"
              accordion
              @node-click="handleNodeClick"
              :filter-node-method="filterNode"
              :highlight-current="tree.highlightSelect"
              :check-on-click-node="tree.checkClick"
              :expand-on-click-node="tree.expandClickNode"
              ref="treeAuth"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ data.name }}</span>
              </span>
            </el-tree>

        </el-card>
      </el-col>










      <el-col :span="16">

        <!--  查询-->
        <el-card>

          <el-form inline label-width="90px" size="mini" class="demo-form-inline">

            <el-form-item label="名称(昵称)">
              <el-input placeholder="请输入用户名称" v-model.trim="searchUserParam.name" clearable size="mini"></el-input>
            </el-form-item>

            <el-form-item label="登录用户名">
              <el-input placeholder="请输入登录用户名" v-model="searchUserParam.loginName" clearable size="mini"></el-input>
            </el-form-item>

            <el-form-item label="性别">
              <el-select v-model="searchUserParam.sex" placeholder="请选择" clearable>
                <el-option
                  v-for="item in sixOpt"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="状态">
              <el-select v-model="searchUserParam.status" placeholder="请选择" clearable>
                <el-option
                  v-for="item in statusOpt"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="success" size="mini" @click="getPageListBefore">查询</el-button>
              <el-button type="info" size="mini" @click="resetQuery">重置</el-button>
              <el-button type="warning" size="mini" @click="openSaveBefore">新增</el-button>
            </el-form-item>

          </el-form>
        </el-card>


        <!--列表部分-->
        <el-card style="margin-top: 10px">

          <el-table
            :data="tableData"
            max-height="650px"
            height="650px"
            style="width: 100%">

            <el-table-column prop="ico" label="" width="50">
              <template slot-scope="scope">
                <el-image class="icoHeadUserImage" fit="contain" :src="scope.row.icoUrl || require('@/assets/images/ico/avatar12.png')" />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="名称(昵称)"/>
            <el-table-column prop="loginName" label="登录用户名"/>
            <el-table-column prop="deptName" label="所属部门"/>
            <el-table-column prop="roleList" label="角色">
              <template slot-scope="scope">
                <span v-for="(item, index) in scope.row.roleList" :key="index">
                  <el-tag size="small">{{scope.row.roleList[index].name}}</el-tag>&nbsp;
                </span>
              </template>
            </el-table-column>

            <el-table-column prop="onLine" label="是否在线">
              <template slot-scope="scope">
                <el-tag size="mini" type="success" v-if="scope.row.onLine === true" >在线</el-tag>
                <el-tag size="mini" v-else type="info">离线</el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="state" label="状态">
              <template slot-scope="scope">
                <el-tag size="mini" type="success" v-if="scope.row.status === 1" >正常</el-tag>
                <el-tag size="mini" v-else-if="scope.row.status === 2" type="warning">停用</el-tag>
                <el-tag size="mini" v-else-if="scope.row.status === 3" type="info">离职</el-tag>
              </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" width="110">
              <template slot-scope="scope">
                <el-button @click="openUserDetailedBefore(scope.row)" type="text" size="small"><i class="el-icon-view"></i>详情
                </el-button>
                <el-dropdown trigger="click">
                  <span class="el-dropdown-link">
                    <el-link style="font-size:12px;line-height: 10px" type="primary" >更多</el-link><i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item>
                      <el-button @click="openUpdBefore(scope.row)" type="text" size="small"><i class="el-icon-edit"></i>编辑
                      </el-button>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-button @click="delTips(scope.row)" type="text" size="small"><i class="el-icon-delete"></i>删除
                      </el-button>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-button @click="kickPeople(scope.row)" type="text" size="small"><i class="el-icon-scissors"></i>踢人下线
                      </el-button>
                    </el-dropdown-item>
                    <el-dropdown-item disabled>
                      <el-button @click="openUpdBefore(scope.row)" type="text" size="small" disabled><i class="el-icon-edit-outline"></i>强制修改密码
                      </el-button>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>





              </template>
            </el-table-column>

          </el-table>


          <!--分页部分-->
          <el-pagination
            style="width:33%; margin-right:10px; margin-top:10px;"
            background
            layout="total, prev, pager, next, jumper"
            @current-change="pageCurrentChange"
            :page-size="pageConfig.size"
            :current-page="pageConfig.current"
            :pager-count="5"
            :total="pageConfig.total">
          </el-pagination>

        </el-card>

      </el-col>
    </el-row>


    <UserSaveUpd ref="UserSaveUpdRef" @getUserPage="getUserPage"/>
    <UserDetailed ref="UserDetailedRef" />

  </div>

</template>


<script>

import http from '@/utils/http'
import {checkNull, clearInvalid} from "@/utils/utils"
import UserSaveUpd from './UserSaveUpd.vue'
import UserDetailed from './UserDetailed.vue'

export default {
  name: "UserList",
  components: {
    UserSaveUpd,
    UserDetailed,
  },
  data() {
    return {
      // 搜索过滤树
      filterText: '',
      // 权限树相关的配置
      tree: {
        // 部门树
        dataTree: [],
        // 是否高亮选中
        highlightSelect: true,
        // 是否在点击节点的时候选中节点，默认值为 false，即只有在点击复选框时才会选中节点。
        checkClick: false,
        // 是否在点击节点的时候展开或者收缩节点， 默认值为 true，如果为 false，则只有点箭头图标的时候才会展开或者收缩节点。
        expandClickNode: false,
      },
      // 查询条件
      searchOpsAuthorityParam:{
        // name: null,
        // code: null,
      },
      // 表格数据
      tableData: [],
      // 分页参数
      pageConfig: {
        // 每页记录数
        size: 20,
        // 当前页码
        current: 1,
        // 总记录数
        total: 0,
      },
      // 查询参数
      searchUserParam: {
        deptId: null,
        deptName: null,
        allSub: 'this',
        name: null,
        loginName: null,
        sex: null,
        status: null,
      },
      // 是否包含全部下级
      checkedAllSub: true,
      // 性别选项
      sixOpt: [
        {key: 0, value: '女性'},
        {key: 1, value: '男性'},
        {key: 9, value: '未知'},
      ],
      // 状态
      statusOpt:[
        {key: 1, value: '正常'},
        {key: 2, value: '停用'},
        {key: 3, value: '离职'},
      ],
    }
  },
  watch: {
    /**
     * 监听值的变化
     * @param val 发生变化的数据
     */
    filterText(val) {
      this.$refs.treeAuth.filter(val);
    }
  },
  methods: {
    /**
     * 渲染图片
     * 只能这样做，图片这里不支持非固定地址返回
     * @param item
     */
    getImageUrlInfo(item) {
      if (!item || !item.ico || item.ico === 'null') {
        // 判空或无效，直接显示默认图
        this.$set(item, 'icoUrl', null);
        return;
      }

      http.getImageUrl(item.ico)
        .then(url => {
          // 异步赋值，触发响应式更新
          this.$set(item, 'icoUrl', url);
        })
        .catch(() => {
          // 下载失败 fallback 默认图
          this.$set(item, 'icoUrl', null);
        });
    },
    /**
     * 删除
     * @param obj 要删除的数据
     */
    delUser(obj) {
      http.post("/user/delUser", {
        id: obj.id,
      }).then(response => {
        let res = response.data;
        if (!res.success) {
          // 401是token过期跳转的
          if (res.code !== 401) {
            this.$message.error(res.msg);
          }
          return
        }

        this.getUserPage()
        this.$message.success("删除成功");

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * 删除之前的提示框
     * @param obj 要删除的数据
     */
    delTips(obj) {
      this.$confirm('是否执行删除, 删除后无法恢复，是否继续?', '提示', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消删除',
        type: 'warning'
      }).then(() => {
        // 确定删除
        this.delUser(obj)

      }).catch(() => {
        // 取消删除
      });
    },
    /**
     * 踢人下线
     * @param row 当前行数据
     */
    kickPeople(row){
      http.post("/admin/kickPeople", {
        userId: row.id,
      }).then(response => {
        let res = response.data;
        if (!res.success) {
          // 401是token过期跳转的
          if (res.code !== 401) {
            this.$message.error(res.msg);
          }
          return
        }

        this.getUserPage()
        this.$message.success("踢人下线成功");

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * 打开修改之前的的弹出框
     * @param obj 修改的值
     */
    openUpdBefore(obj) {
      this.$refs.UserSaveUpdRef.init('upd', obj)
    },
    /**
     * 打开详情
     */
    openUserDetailedBefore(obj){
      this.$refs.UserDetailedRef.openDetailed(obj)
    },
    /**
     * 打开保存的弹框
     */
    openSaveBefore() {
      if (checkNull(this.searchUserParam.deptId)){
        this.$message.warning("请选择部门");
        return
      }
      this.$refs.UserSaveUpdRef.init('save', this.searchUserParam)
    },
    /**
     * 重置查询条件
     */
    resetQuery() {
      this.searchUserParam = {
        deptId: null,
        deptName: null,
        allSub: 'this',
        name: null,
        loginName: null,
        sex: null,
        status: null,
      }
    },
    /**
     * 分页查询列表
     */
    getUserPage() {
      if (checkNull(this.searchUserParam.deptId)){
        this.$message.warning("请选择部门");
        return
      }
      if (this.checkedAllSub){
        this.searchUserParam.allSub = 'all'
      } else {
        this.searchUserParam.allSub = 'this'
      }
      this.searchUserParam.current = this.pageConfig.current
      this.searchUserParam.size = this.pageConfig.size
      http.post("/user/getUserPage", this.searchUserParam).then(response => {
        let res = response.data;
        // 分页数据
        let data = res.data;
        this.pageConfig.total = data.total;
        this.pageConfig.current = data.current;
        this.pageConfig.size = data.size;
        // 表格数据
        this.tableData = data.records
        // 异步加载每个图片
        this.tableData.forEach(item => this.getImageUrlInfo(item));

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * 分页前重置分页参数
     */
    getPageListBefore() {
      this.pageConfig.current = 1
      this.getUserPage()
    },
    /**
     * 分页被改变的时候
     * @param value 当前页
     */
    pageCurrentChange(value) {
      this.pageConfig.current = value
      this.getUserPage()
    },
    /**
     * 节点被点击时的回调
     * @param data 当前被选中的节点
     */
    handleNodeClick(data){
      this.searchUserParam.deptId = data.id
      this.searchUserParam.deptName = data.name
      this.getUserPage()
    },
    /**
     * 过滤查询树
     * @param value 要过滤的值，查询的数据
     * @param data 当前节点数据
     * @param node 节点信息
     * @return {boolean}  返回 true 表示这个节点可以显示，返回 false 则表示这个节点会被隐藏
     */
    filterNode(value, data, node) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    /**
     * 获取部门树
     */
    getDepTree() {
      http.post("/dep/getDepTree", null).then(response => {
        let res = response.data;
        if (!res.success) {
          // 401是token过期跳转的
          if (res.code !== 401) {
            this.$message.error(res.msg);
          }
          return
        }
        // 表格数据
        this.tree.dataTree = res.data
        this.searchUserParam.deptId = res.data[0].id
        this.searchUserParam.deptName = res.data[0].name
        this.getUserPage()

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
  },
  // 进入马上执行
  mounted() {
    this.$store.commit('navigationListChange', [
      {name: '用户', url: '/toUserList', query: {}}
      // {name: '场所详情', url: '/toSiteLayout', query: {siteId: this.$route.query.siteId}},
    ])
    this.getDepTree()
  },
}
</script>

<style >

/*头像的样式*/
.icoHeadUserImage{
  width: 30px;
  height: 30px;
}

/*
添加虚线 start
需要去掉 style 去掉scoped
需要在 el-tree 上添加 class="tree-line" :indent='0' 这2个属性
*/

/*缩进量*/
.tree-line .el-tree-node {
  position: relative;
  padding-left: 16px;
}

/*缩进量*/
.tree-line .el-tree-node__children {
  padding-left: 16px;
}

/*竖线*/
.tree-line .el-tree-node::before {
  content: '';
  height: 100%;
  width: 1px;
  position: absolute;
  left: -3px;
  top: -26px;
  border-width: 1px;
  border-left: 1px dashed #52627c;
}

/*当前层最后一个节点的竖线高度固定*/
.tree-line .el-tree-node:last-child::before {
  height: 38px;
}

/*横线*/
.tree-line .el-tree-node::after {
  content: '';
  width: 24px;
  height: 20px;
  position: absolute;
  left: -3px;
  top: 12px;
  border-width: 1px;
  border-top: 1px dashed #52627c;
}

/*去掉最顶层的虚线，放最下面样式才不会被上面的覆盖了*/
.tree-line > .el-tree-node::after {
  border-top: none;
}
.tree-line > .el-tree-node::before {
  border-left: none;
}

/*展开关闭的icon*/
.tree-line .el-tree-node__expand-icon {
  font-size: 16px;
}
/*叶子节点（无子节点）*/
.tree-line .el-tree-node__expand-icon.is-leaf {
  color: transparent;
}

/*
添加虚线 end
需要去掉 style 去掉scoped
*/

</style>
